import api from '@/services/welcome';
import { formatUTCTime } from '@/utils/format';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Card, DatePicker } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useRef, useState } from 'react';
import style from './style.less';

const dateFormat = 'YYYY-MM-DD';
const timeFormat = 'YYYY-MM-DD HH:mm:ss';
/**
 * 每个单独的卡片，为了复用样式抽成了组件
 * @param param0
 * @returns
 */

export const getStatistics = async (params: WelcomeApi.Params) => {
  const res = await api.getStatistics(params);

  return res.data;
};
export const getStatisticsList = async (params: WelcomeApi.Params) => {
  const res = await api.getStatisticsList(params);
  const tableData: Requestor.TableFormatedData<WelcomeApi.StatisticsListInfoResponse> = {
    data: res.data,
    success: res.success,
  };

  return tableData;
};
function Home() {
  const { initialState } = useModel('@@initialState');
  const actionRef = useRef<ActionType>();

  const [params, setParams] = useState(() => {
    const period = 7;
    return {
      startTime: dayjs()
        .subtract(period - 1, 'days')
        .startOf('day')
        .format(timeFormat),
      endTime: dayjs().endOf('day').format(timeFormat),
    };
  });
  const [statistics, setStatistics] = useState<Partial<WelcomeApi.StatisticsInfoResponse>>({});
  const [statisticsList, setStatisticsList] = useState<
    readonly WelcomeApi.StatisticsListInfoResponse[]
  >([]);

  const statisticsOptions = useMemo(() => {
    const options: { label: string; value: any }[] = [];
    const config: { [key in keyof WelcomeApi.StatisticsInfoResponse]: string } = {
      issueSingleNumber: '出单台次',
      numberOfDefeats: '战败台次',
      grossPremium: '保费总额',
      commercialPremium: '商业保费',
      mandatoryPremium: '交强保费',
      vesselTax: '车船税',
      drivingIntention: '驾意险',
      plannedFollowUp: '计划回访',
      actualFollowUp: '实际回访',
      followUpNumber: '回访次数',
    };
    const keys = Object.keys(statistics) as (keyof WelcomeApi.StatisticsInfoResponse)[];
    for (let key of keys) {
      options.push({ label: config[key], value: statistics[key] });
    }
    return options;
  }, [statistics]);

  const getStatisticsRequest = async (params: WelcomeApi.Params) => {
    const data = await getStatistics(params);
    setStatistics(data);
  };
  const getStatisticsListRequest = async (params: WelcomeApi.Params) => {
    const res = await getStatisticsList(params);
    setStatisticsList(res.data);
  };

  useEffect(() => {
    onSearch();
  }, [params.startTime, params.endTime]);

  const onSearch = () => {
    getStatisticsRequest({
      startTime: formatUTCTime(params.startTime),
      endTime: formatUTCTime(params.endTime),
    });
    getStatisticsListRequest({
      startTime: formatUTCTime(params.startTime),
      endTime: formatUTCTime(params.endTime),
    });
  };
  const columns = useMemo(() => {
    const tableColumns: ProColumns<WelcomeApi.StatisticsListInfoResponse>[] = [
      {
        title: '用户账号',
        dataIndex: 'username',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '出单台次',
        dataIndex: 'issueSingleNumber',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '战败台次',
        dataIndex: 'numberOfDefeats',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '保费总额',
        dataIndex: 'grossPremium',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '商业保费',
        dataIndex: 'commercialPremium',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '交强保费',
        dataIndex: 'mandatoryPremium',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '车船税',
        dataIndex: 'vesselTax',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '驾意险',
        dataIndex: 'drivingIntention',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '计划回访',
        dataIndex: 'plannedFollowUp',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '实际回访',
        dataIndex: 'actualFollowUp',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '回访次数',
        dataIndex: 'followUpNumber',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
    ];
    return tableColumns;
  }, []);
  return (
    <div className={style.home}>
      <div className={style.header}>
        <div className={style.tabs}>
          <div className={style.tabsItem}>续保</div>
        </div>
        {/* <Tabs size="middle" items={[{ key: '1', label: '续保' }]} /> */}
      </div>
      <Card className={style.card}>
        <div className={style.cardHead}>
          <div className={style.cardTitle}>人员效能</div>
        </div>
        <div className={style.cardFilter}>
          <div className={style.cardFilterMain}>
            <div className={style.cardFilterLabel}>统计时间：</div>
            <DatePicker.RangePicker
              allowClear={false}
              format={dateFormat}
              value={[dayjs(params.startTime, dateFormat), dayjs(params.endTime, dateFormat)]}
              onChange={(_, date) => {
                const [start, end] = date;
                const startTime = dayjs(start).startOf('day').format(timeFormat);
                const endTime = dayjs(end).endOf('day').format(timeFormat);
                setParams({ startTime, endTime });
              }}
            />
          </div>
          <div className={style.cardFilterTools}>
            <Button type="primary" onClick={onSearch}>
              查询
            </Button>
          </div>
        </div>
        <div className={style.cardList}>
          {statisticsOptions.map((item, i) => {
            return (
              <div className={style.cardItem} key={i}>
                <div className={style.cardItemContent}>
                  <div className={style.cardItemLabel}>{item.label}</div>
                  <div className={style.cardItemValue}>{item.value}</div>
                </div>
              </div>
            );
          })}
        </div>
        <ProTable
          className={style.cardTable}
          bordered
          rowKey="id"
          search={false}
          options={false}
          actionRef={actionRef}
          pagination={false}
          columns={columns}
          dataSource={statisticsList}
        />
      </Card>
    </div>
  );
}

export default Home;
